package com.qikux.service.impl;

import com.qikux.annotation.Component;
import com.qikux.annotation.Transactional;
import com.qikux.consts.AppConst;
import com.qikux.dao.DetailDao;
import com.qikux.dao.UserDao;
import com.qikux.entity.*;
import com.qikux.service.DetailService;
import com.qikux.utils.ContextUtils;
import com.qikux.utils.RSAUtils;
import com.qikux.vo.Page;
import com.qikux.vo.ResourceVo;
import com.qikux.vo.ResultVo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class DetailServiceImpl implements DetailService {

    @com.qikux.annotation.Resource
    private DetailDao detailDao;

    @com.qikux.annotation.Resource
    private UserDao userDao;

    /**
     * 通过资源id查找资源
     * @param resId
     * @return
     */
    @Override
    public ResultVo<ResourceVo> queryResourceById(Long resId, User user) {

        if (user == null) {
            // 通过数据传输层查询 根据资源id 查询该资源
            ResourceVo resource = detailDao.findResourceById(resId);
            // 当查找到的资源为空的时候,返回失败状态并将错误消息设置为  找不到对应的资源
            if (resource == null){
                return ResultVo.fail("找不到对应的资源").build();
            }
            // 查找到该资源时, 返回成功的状态，同时返回该资源
            return ResultVo.ok().body(resource);
        }
        // 否则  查询 资源和 收藏状态
        ResourceVo resourceVo = detailDao.findResourceById(resId , user.getId());
        if (resourceVo == null){
            return ResultVo.fail("找不到对应的资源").build();
        }
        return ResultVo.ok().body(resourceVo);

    }

    @Override
    public ResultVo<String> collect(Long resId, Long userId) {

        ResourceCollection resourceCollection = detailDao.collect(resId, userId);
        //查询资源上传者
        ResourceVo resource = detailDao.findResourceById(Long.valueOf(resId));
        if(resource.getUserId().equals(userId)){
            return ResultVo.fail("不能收藏自己的资源").body("不能收藏自己的资源");
        }
        if (resourceCollection == null){
            detailDao.saveCollection(resId,userId);
            ResourceVo resourceById = detailDao.findResourceById(resId);
            User user = (User) ContextUtils.getSession().getAttribute(AppConst.LOGIN_FLAG);
            Notice notice = Notice.builder()
                    .remark(AppConst.COLLECT)
                    .content(user.getInfo().getNickName() + AppConst.content_COLLECT + "《"+resourceById.getResourceName()+"》")
                    .userId(resourceById.getUserId())
                    .tagUserId(user.getId())
                    .resId(resId)
                    .build();
            Notice notice1 = detailDao.findNoticeByUserIdAndContent(notice);
            if (notice1 == null){
                detailDao.saveNotice(notice);
            }
            return ResultVo.ok().body("收藏成功");
        }

        detailDao.deleteCollection(resId,userId);

        return ResultVo.ok().body("取消收藏成功");
    }

    @Override
    public ResultVo<Page<Map<String, Object>>> comment(Long resId, Page<Map<String, Object>> pageBean) {
        // 查询指定页码的数据
        List<Map<String, Object>> list = detailDao.findResourceCommentByResId(resId,pageBean);
        // 查询满足条件的总个数
        int count = detailDao.findCommnetByResId(resId);

        pageBean.setList(list);
        pageBean.setTotalRows(count);
        return ResultVo.ok().body(pageBean);
    }

    @Override
    public UserInfo queryUserInfoByUserId(Long userId) {
        return detailDao.findUserInfoByUserId(userId);
    }

    @Override
    public Map<String,Object> getPhotoPath(Long userId) {
        return detailDao.findPhotoByUserId(userId);
    }

    @Override
    public int queryDownloadCount(Long resId) {
        return detailDao.findDownloadCount(resId);
    }

    @Override
    public ResultVo<Map<String,Object>> isSelfRes(User user, Long resId) {
        Map<String,Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        // 根据用户id和资源id查询对应的资源
        Resource resourceByUserId = detailDao.findResourceByUserId(user.getId(), resId);
        // 找到对应的资源时候 说明资源是自己的 不扣积分 也不记录
        if (resourceByUserId != null){
            map.put("record",0);
            map.put("deduct",0);
            map.put("score",resourceByUserId.getScore());
            sb.append("?record=0").append("&deduct=0").append("&score="+resourceByUserId.getScore());
            map.put("sign", RSAUtils.sign(sb.toString()));
            return ResultVo.ok().body(map);
        }

        // 当资源不是自己的时候
        // 根据资源id查到对应的该资源
        Resource resourceById = detailDao.findResourceById(resId);
        // 查询近30天是否下载果该资源
        List<Map<String,Object>> mapp = detailDao.findDownLoadTime(user.getId(),resId);

        if (!mapp.isEmpty()) {
            detailDao.saveResourceHistory(user.getId(),resId);
            map.put("record",1);
            map.put("deduct",0);
            map.put("score",resourceById.getScore());
            sb.append("?record=1").append("&deduct=0").append("&score="+resourceById.getScore());
            map.put("sign", RSAUtils.sign(sb.toString()));
            // 不扣积分,将下载记录存到下载资源表中
            return ResultVo.ok().body(map);
        }

        // 获取下载该资源所需要的积分
        int score = resourceById.getScore();

        if (score == 0){
            map.put("record",1);
            map.put("deduct",0);
            map.put("score",0);
            sb.append("?record=1").append("&deduct=0").append("&score=0");
            map.put("sign", RSAUtils.sign(sb.toString()));
            detailDao.saveResourceHistory(user.getId(),resId);
            return ResultVo.ok().body(map);
        }
        // 获取用户的积分
        int userScore = detailDao.findScoreByUserId(user.getId());
        // 如果用户积分小于下载资源所需的积分 不记录本次下载记录,返回积分不足
        if (userScore < score){
            return ResultVo.fail("积分不足").build();
        }

        // 获取上传该资源的用户id
        Long uploadUserId = resourceById.getUserId();
        map.put("record",1);
        map.put("deduct",1);
        map.put("score",resourceById.getScore());
        sb.append("?record=1").append("&deduct=1").append("&score="+resourceById.getScore());
        map.put("sign", RSAUtils.sign(sb.toString()));
        // 插入当前用户积分记录
        UserScore userScore1 = UserScore.builder()
                .remark(AppConst.REMARK_DOWNLOAD)
                .userId(user.getId())
                .score(-score)
                .resId(resId)
                .build();
        userDao.saveUserScore(userScore1);
        // 将该记录存入到资源下载记录表中
        detailDao.saveResourceHistory(user.getId(),resId);
        // 插入上传该资源的用户的积分
        UserScore userScore2 = UserScore.builder()
                .remark(AppConst.REMARK_BEDOWNLOAD)
                .resId(resId)
                .userId(resourceById.getUserId())
                .score(1)
                .build();
        userDao.saveUserScore(userScore2);
        return ResultVo.ok().body(map);
    }
}
